function [Child1, Child2] = adaptiveCrossover(Parent1, Parent2, params)
    % Adaptive two-point crossover for potentially heterogeneous chromosomes.
    if isempty(Parent1) || isempty(Parent2)
        warning('Cannot perform crossover with empty parent(s).');
        Child1 = Parent1; Child2 = Parent2;
        return;
    end

    M = params.M;
    rows1 = size(Parent1, 1);
    rows2 = size(Parent2, 1);

    Child1 = zeros(rows1, M); % Inherit parent's row count initially
    Child2 = zeros(rows2, M);

    % Choose two distinct crossover points (columns)
    cx_points = sort(datasample(1:M, 2, 'Replace', false));
    p1 = cx_points(1);
    p2 = cx_points(2);

    % Get module assignments (maps element index to module index)
    [map1, ~] = find(Parent1');
    [map2, ~] = find(Parent2');
    
    if length(map1) ~= M || length(map2) ~= M
         warning('Invalid parent chromosome structure in crossover.');
         Child1 = Parent1; Child2 = Parent2; % Return originals
         return;
    end

    new_map1 = map1;
    new_map2 = map2;

    % Swap module assignments between the crossover points
    for j = p1:p2
        new_map1(j) = map2(j); % Child 1 gets module index from Parent 2
        new_map2(j) = map1(j); % Child 2 gets module index from Parent 1
    end

    % Reconstruct children, handling potential out-of-bounds module indices
    for j = 1:M
        % Child 1
        target_module1 = new_map1(j);
        if target_module1 > rows1 || target_module1 < 1 % Check bounds
            target_module1 = randi(rows1); % Randomly re-assign if out of bounds
        end
        Child1(target_module1, j) = 1;

        % Child 2
        target_module2 = new_map2(j);
        if target_module2 > rows2 || target_module2 < 1 % Check bounds
            target_module2 = randi(rows2); % Randomly re-assign if out of bounds
        end
        Child2(target_module2, j) = 1;
    end

    % Validate children
    if ~all(sum(Child1, 1) == 1) || ~all(sum(Child2, 1) == 1)
        % warning('Crossover resulted in invalid children. Returning parents.');
        Child1 = Parent1; % Return originals if validation fails
        Child2 = Parent2;
    end
end
